<?php
function curl_fetch($url, $timeout = 1, &$ch = null) {
	$init_ch = true;
	if (!isset($ch)) {
		$init_ch = false;
		$ch = curl_init();

		curl_setopt($ch, CURLOPT_HEADER, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		curl_setopt($ch, CURLOPT_AUTOREFERER, true);
	} 
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
	$data = curl_exec($ch);
	$errno = curl_errno($ch);

	if ($errno > 0) {
		$err = "[CURL] url:{$url} errno:{$errno} info:" . curl_error($ch) . "\n";
		error_log($err);
		$data = false;
	} 
	if (!$init_ch) {
		curl_close($ch);
	} 
	return $data;
} 


/**
 * convert xml to array
 * 
 * @param string $string 
 * @param string $encoding 
 * @return array $mnary
 */
function xml_array(&$string, $encoding = "GBK") {
	$parser = xml_parser_create();
	xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
	$is_parse = @xml_parse_into_struct($parser, $string, $vals, $index);
	if ($is_parse == 0)
		return array();
	xml_parser_free($parser);

	$mnary = array();
	$ary = &$mnary;
	foreach ($vals as $r) {
		$t = $r["tag"];
		if ($r["type"] == 'open') {
			if (isset($ary[$t])) {
				if (isset($ary[$t][0]))
					$ary[$t][] = array();
				else
					$ary[$t] = array($ary[$t], array());
				$cv = &$ary[$t][count($ary[$t]) - 1];
			} else
				$cv = &$ary[$t];
			if (isset($r["attributes"])) {
				foreach ($r["attributes"] as $k => $v)
				$cv["_a"][$k] = $v;
			} 
			$cv["_c"] = array();
			$cv["_c"]["_p"] = &$ary;
			$ary = &$cv["_c"];
		} elseif ($r["type"] == 'complete') {
			if (isset($ary[$t])) { // same as open
				if (isset($ary[$t][0]))
					$ary[$t][] = array();
				else
					$ary[$t] = array($ary[$t], array());
				$cv = &$ary[$t][count($ary[$t]) - 1];
			} else
				$cv = &$ary[$t];
			if (isset($r["attributes"])) {
				foreach ($r["attributes"] as $k => $v)
				$cv["_a"][$k] = $v;
			} 
			if (isset($r["value"])) {
				if ($encoding == "GBK")
					$r["value"] = iconv("UTF-8", "GBK//IGNORE", $r["value"]);
				$cv["_v"] = $r["value"];
			} else {
				$cv["_v"] = "";
			} 
		} elseif ($r["type"] == 'close') {
			$ary = &$ary["_p"];
		} 
	} 

	_del_p($mnary);
	return $mnary;
} 

// _Internal: Remove recursion in result array
function _del_p(&$ary) {
	foreach ($ary as $k => $v) {
		if ($k === '_p')
			unset($ary[$k]);
		elseif (is_array($ary[$k]))
			_del_p($ary[$k]);
	} 
} 


function unicode_hex_2_GBK($name) {
	$a = json_decode('{"a":"' . $name . '"}');
	return iconv('UTF-8', 'GBK', $a -> a);
} 
?>